// 启动一个 chrome 实例
// 提取页面元素

/**
 * Launches a debugging instance of Chrome.
 * @param {boolean=} headless True (default) launches Chrome in headless mode.
 *     False launches a full version of Chrome.
 * @return {Promise<ChromeLauncher>}
 */

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');

function launchChrome(headless=true) {
	return chromeLauncher.launch({
		chromePath: 'google-chrome',
		port: 9922,
		logLevel: 'verbose',
		chromeFlags: [
			'--window-size=1440,1080',
			'--disable-gpu',
			'--no-sandbox',
			headless ? '--headless' : ''
		]
	});
}

launchChrome().then(async chrome => {
	console.log(`Chrome debuggable on port: ${chrome.port}`);
	// print the user agent
	const {Page, Runtime} = await CDP({port: chrome.port});
	// console.log(Version['User-Agent']);
	// create new tab and navigate to url
	await Promise.all([Page.enable(), Runtime.enable()]);
	
	// Wait for window.onload before doing stuff.
	Page.loadEventFired(async () => {
		const js = "document.querySelector('title').textContent";
		const result = await Runtime.evaluate({expression: js});
		console.log('Title of page: ' + result.result.value);
		
		chrome.kill()
	})

	let url = 'http://www.baidu.com';
	Page.navigate({url: url});
});

